import axios from "axios";
import {Message} from "view-design";
import router from "../router"
import settings from "../settings";

let base = settings.HOST

axios.defaults.withCredentials = false


// 客户端请求拦截器
axios.interceptors.request.use(config => {
    // 如果客户端的localStorage中，存在token，则请求的时候，带上这个token
    let user_info = localStorage.getItem('user_info')
    if (user_info) {
        config.headers['Authorization'] = 'JWT ' + JSON.parse(user_info).token
    }
    return config;
}, error => {
    console.log(error)
})


// 服务端响应拦截器
axios.interceptors.response.use(success => {
    // 请求成功，但是服务端业务逻辑错误
    if (success.status && success.status === 200) {
        if (success.data.code === 500 || success.data.code === 401 || success.data.code === 403) {
            Message.error({content: success.data.message});
            return;
        }
        if (success.data.message) {
            Message.success({content: success.data.message});
        }
    }
    return success;
}, error => {
    // 请求错误，服务器挂掉了
    if (error.response.status === 504 || error.response.status === 404) {
        if (error.response.data.message){
            Message.error({content: error.response.data.message});
        } else {
            Message.error({content: '服务器资源未找到，请检查！'});
        }
    }else if (error.response.status === 403) {
        Message.error({content: '权限不足，请联系管理员！'});
    }else if (error.response.status === 401) {
        Message.error({content: '尚未登录，请登录！'});
        localStorage.clear()
        router.replace('/login').then(r => {});
    }else if (error.response.status === 400) {
        if (error.response.data.message){
            Message.error({content: error.response.data.message});
        } else {
            Message.error({content: '用户名或密码错误，请检查！'});
        }
    } else {
        if (error.response.data.message){
            Message.error({content: error.response.data.message});
        } else {
            Message.error({content: '请求错误，请检查！'});
        }
    }
});


// 封装json的post请求
export const postRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params
    })
}

// 封装json的post请求
export const getRequest = (url, params) => {
    return axios({
        method: 'get',
        url: `${base}${url}`,
        data: params
    })
}


// 封装json的put请求
export const putRequest = (url, params) => {
    return axios({
        method: 'put',
        url: `${base}${url}`,
        data: params
    })
}

// 封装json的delete请求
export const deleteRequest = (url, params) => {
    return axios({
        method: 'delete',
        url: `${base}${url}`,
        data: params
    })
}